package com.jiu345.users.service.impl;

import cn.dev33.satoken.stp.StpUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.jiu345.core.page.PageQuery;
import com.jiu345.core.page.TableDataInfo;
import com.jiu345.users.mapper.AddressMapper;
import com.jiu345.users.mapper.UserMapper;
import com.jiu345.users.pojo.Address;
import com.jiu345.users.pojo.Member;
import com.jiu345.users.service.IAddressService;
import com.jiu345.users.service.IUserService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.Collection;
import java.util.List;

/**
 * @author MrLei QQ:235921049
 * desc:用户地址
 * @Date 2024.07.29 08:17
 */
@RequiredArgsConstructor
@Service
public class IAddressServiceImpl implements IAddressService {
    private final AddressMapper baseMapper;

    /*根据用户ID查询收货地址*/
    @Override
    public TableDataInfo<Address> queryPageList(Address bo, PageQuery pageQuery) {
        Page<Address> result = baseMapper.queryPageList(pageQuery.build(), bo);
        //把省市区地址拼接
//        result.getRecords().forEach(addr -> {
//            addr.setFullLocation(addr.getProvinceName() +" " + addr.getCityName()+" " + addr.getDistrictName());
//        });
        return TableDataInfo.build(result);
    }

    /*新增用户收货地址*/
    @Override
    public Boolean insertByBo(Address bo) {
        validEntityBeforeSave(bo);
        //

        return baseMapper.insert(bo) > 0;
    }

    /*根据主键查询*/
    @Override
    public Address queryById(Long id) {
        return baseMapper.selectById(id);
    }

    /*修改用户收货地址*/
    @Override
    public Boolean updateByBo(Address bo) {
        if(baseMapper.updateById(bo) > 0 && bo.getIsDefault()==1) {
            //将其他默认值改为0
            updateDefaultStatus(bo.getId());
        }
        return true;
    }

    /*设置默认地址*/
    @Override
    public Boolean updateStatus(Long id) {
        //把传入id对应的is_default改成1
        try {
            baseMapper.update(Address.builder().isDefault(1).build(), new LambdaQueryWrapper<Address>().eq(Address::getId, id));
        } catch (Exception e) {
            throw new RuntimeException("修改当前id的默认地址状态失败"+e);
        }
        //如果传入id对应的is_default改成1成功，就调用updateDefaultStatus，将该用户的其他地址默认状态取消，
        updateDefaultStatus(id);
        return true;
    }
    /*删除地址*/
    @Override
    public Boolean deleteWithValidByIds(Collection<String> ids, Boolean isValid) {
        if(isValid){
            //TODO 做业务上的校验
        }
        return baseMapper.deleteByIds(ids) > 0;
    }


    /**
     * 更新默认收货地址状态
     *
     * @param id 收货地址id
     */
    private void updateDefaultStatus(Long id) {
        Address defaultAddress = new Address();
        //设置为非默认收货地址，便于给update方法用
        defaultAddress.setIsDefault(0);

        //根据id查询用户的userId
        Long userId = baseMapper.selectById(id).getUserId();

        LambdaQueryWrapper<Address> lqw = new LambdaQueryWrapper<>();
        //将同一个userId下其他id所属的地址，的默认状态改成1
        lqw.eq(Address::getUserId, userId).ne(Address::getId, id);
        System.out.println("这里是分节");
        baseMapper.update(defaultAddress,lqw);
    }

    /*地区编码组件*/

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(Address entity) {
        //TODO 做一些数据校验,如唯一约束
        //entity.setUpdateBy(SecurityUtils.getCurrentUserId());
    }
}
